"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.transpileCommonIfChange = void 0;
const child_process = __importStar(require("child_process"));
const git_utils_1 = require("../utils/git-utils");
const cache_1 = require("../utils/cache");
const fs = __importStar(require("fs-extra"));
// import { getAllAppPackages } from '../utils/getAllAppPackages';
const path = require('path');
const transpile = (options = {}) => __awaiter(void 0, void 0, void 0, function* () {
    process.env.NODE_ENV = process.env.NODE_ENV || 'production';
    require('../config/env');
    const paths = require('../config/paths');
    const { sourceDir = './src', libDir = './lib', subModule, SKIP_NO_CHANGE_MODULE = process.env.SKIP_NO_CHANGE_MODULE === 'true', } = options;
    let cwd = process.cwd();
    // 编译子模块项目
    if (subModule) {
        cwd = path.resolve(paths.appRootPath, 'packages', subModule);
        if (!fs.existsSync(cwd)) {
            console.log(`请检查子模块目录是否存在:\n${cwd}\n`);
            process.exit(1);
            return;
        }
    }
    let packagePath = path.resolve(cwd, 'package.json');
    let srcPath = path.resolve(cwd, sourceDir);
    let libsPath = path.resolve(cwd, libDir);
    if (!fs.existsSync(packagePath) || !fs.existsSync(srcPath)) {
        console.log(`请检查以下文件或目录是否存在:\n${srcPath}\n${packagePath}\n`);
        process.exit(1);
        return;
    }
    const packageInfo = fs.readJSONSync(packagePath);
    const { name } = packageInfo;
    if (SKIP_NO_CHANGE_MODULE && fs.existsSync(libsPath)) {
        try {
            let packageFilesIsNotChange = false;
            const cacheData = yield cache_1.getCachedData(`transpile_${name}`);
            if (cacheData) {
                packageFilesIsNotChange = !(yield git_utils_1.fileHasChangeFromCommit(`packages/${name}`, cacheData));
            }
            if (packageFilesIsNotChange) {
                console.log(`${packageInfo.name} 模块文件没有变化，跳过 transpile`);
                return 'skip';
            }
        }
        catch (_a) { }
    }
    yield new Promise((resolve, reject) => {
        // babel 编译 es6
        console.log(`正在 transpile ${name} 模块`);
        let babelBin = 'babel';
        try {
            babelBin = `node \"${require.resolve('@babel/cli/bin/babel.js', {
                paths: [cwd, paths.appRootPath],
            })}\"`;
        }
        catch (e) {
            console.log(e);
        }
        const cmd = `${babelBin} \"${srcPath}\" --delete-dir-on-start --include-dotfiles --extensions .js,.jsx,.ts,.tsx --out-dir lib --copy-files --ignore \"src/**/*.spec.js\",\"src/**/*.test.js\"`;
        child_process.exec(cmd, {
            cwd,
            env: Object.assign(Object.assign({}, process.env), { NODE_ENV: 'production', BABEL_ENV: 'production' }),
        }, (error, stdout) => {
            console.log(stdout);
            if (error) {
                return reject(error);
            }
            else {
                resolve({
                    stdout,
                    cwd,
                    packageInfo,
                });
            }
        });
    })
        .then(() => {
        // 生成类型声明文件
        console.log(`正在 typescript 编译 ${name} 模块`);
        let tscBin = 'tsc';
        try {
            tscBin = `node \"${require.resolve('typescript/lib/tsc.js', {
                paths: [cwd, paths.appRootPath],
            })}\"`;
        }
        catch (e) {
            console.log(e);
        }
        const cmd = tscBin;
        return new Promise((resolve, reject) => {
            child_process.exec(cmd, {
                cwd,
                env: Object.assign({}, process.env),
            }, (error, stdout) => {
                console.log(stdout);
                if (error) {
                    return reject(error);
                }
                else {
                    resolve(stdout);
                }
            });
        });
    })
        .catch((msg) => {
        console.error(msg);
        // process.exit(1);
        return Promise.resolve();
    });
    yield cache_1.setCachedData(`transpile_${name}`, yield git_utils_1.getHeadId());
    return 'transpile';
});
/**
 * 当 common 模块未编译时, 编译 common 模块
 */
function transpileCommonIfChange() {
    return __awaiter(this, void 0, void 0, function* () {
        let subModules = [];
        const paths = require('../config/paths');
        const cpaasConfig = paths.getCpaasBootConfig(paths.appPath) || {};
        subModules = cpaasConfig.common || [];
        // || getAllAppPackages(
        //   '{*-common,cpaas-front,*-front}'
        // );
        if (typeof subModules === 'string') {
            subModules = [subModules];
        }
        if (!subModules || !subModules.length) {
            return [];
        }
        const transpiledModules = [];
        for (const subModuleItem of subModules) {
            if ((yield transpile({
                subModule: subModuleItem,
                SKIP_NO_CHANGE_MODULE: true,
            })) === 'skip') {
                continue;
            }
            transpiledModules.push(subModuleItem);
        }
        return transpiledModules;
    });
}
exports.transpileCommonIfChange = transpileCommonIfChange;
const bootstrap = (options = {}) => __awaiter(void 0, void 0, void 0, function* () {
    return transpile(options);
});
exports.default = bootstrap;
